/**
 * 严肃声明：
 * 开源版本请务必保留此注释头信息，若删除我方将保留所有法律责任追究！
 * 本系统已申请软件著作权，受国家版权局知识产权以及国家计算机软件著作权保护！
 * 可正常分享和学习源码，不得用于违法犯罪活动，违者必究！
 * Copyright (c) 2020 陈尼克 all rights reserved.
 * 版权所有，侵权必究！
 */
import axios from "axios";
import { getToken, setToken } from "@/utils/auth.js";
import router from "../router";
import { useUser } from "@/stores/user"
import { showToast, showFailToast, showConfirmDialog } from "vant";
// const baseURL = window.location.host.indexOf("localhost") > -1 ? window.location.origin : "https://mhlrj.shmh.gov.cn/zhkp"
const baseURL = "https://mhlrj.shmh.gov.cn"
const instance = axios.create({
  baseURL,
  timeout: 5000
})


instance.interceptors.request.use(
  (config) => {
    config.headers["token"] = getToken();
    return config;
  },
  (error) => {
    if (error.code === "ECONNABORTED" && error.message.indexOf("timeout") !== -1) {
      showFailToast("请求超时！");
    }
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  (res) => {
    const { code } = res.data
    if (code == '-201') {
      const userStore = useUser()
      userStore.resetToken().then(() => {
        showToast('登录已过期，请重新登录')
        router.push({ path: "/login" });
      });
    }
    return res.data;
  },
  (error) => {
    console.log("🚀 ~ error:", error)
    const { status, response } = error
    if (status == 401 && (response.data.code == -101 || response.data.code == -202)) {
      const userStore = useUser()
      userStore.resetToken().then(() => {
        showToast('登录已过期，请重新登录')
        router.push({ path: "/login" });
      });
    }
    // return Promise.reject(error);
  }
);

export default instance;

